//
//  NewFeatureViewController.swift
//  SinaMicroBlog
//
//  Created by wxy on 15/9/6.
//  Copyright © 2015年 wxy. All rights reserved.
//

import UIKit

// 可重用cell
private let NewFeatureCellID = "NewFeatureCellID"
// 新特性图片的数量
private let NewFeatureCount = 4

class NewFeatureViewController: UICollectionViewController {
    
    // 使用collectionViewCell时,必须有一个非空的layout属性
    init() {
        // 调用父类的默认构造函数
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        
        super.viewDidLoad()
        // 注册可重用cell
        self.collectionView?.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier:
        NewFeatureCellID)
        
        prepareLayout()
    }
    
    private func prepareLayout() {
        
        // 获得当前的布局属性
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return NewFeatureCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NewFeatureCellID, forIndexPath: indexPath) as! NewFeatureCell
        
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    // indexPath 参数是之前显示的cell的indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 取出当前显示cell的index
        let path = collectionView.indexPathsForVisibleItems().last!
       
        // 判断是不是最后一个
        if path.item == NewFeatureCount - 1 {
            
            // 获取cell
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            
            cell.showStartButton()
        }
    }
}
    
// 新特性cell，private保证cell只被当前控制器使用，当前文件中，所有的private都是摆设
private class NewFeatureCell: UICollectionViewCell {
    
    // frame的大小来自于 layout的itemSize
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 图像索引属性
    var imageIndex: Int = 0 {
        
        // 根据索引设置图片
        didSet {
            iconImageView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            
            startButton.hidden = true
        }
        
    }
    
    @objc func clickStartButton() {
        
        //切换到Main
        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: nil)
    }
    
    // 动画显示启动按钮
    private func showStartButton() {
        
        startButton.hidden = false
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // Damping 弹性系数 0~1 越小越弹
        // Velocity 初始速度
        UIView.animateWithDuration(1.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: { () -> Void in
            
            // 恢复初始的形变
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                
        }
        
    }
    
    private func setUpUI() {
        
        // 这时候控件已经有大小了
        //printLog(bounds)
        
        // 添加控件
        addSubview(iconImageView)
        addSubview(startButton)
        // 指定布局
        iconImageView.frame = bounds
        
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        //自动布局约束到父视图上
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
}

    // MARK: - 懒加载属性
    // 图像
    private lazy var iconImageView = UIImageView()
    
    // 开始体验按钮
    private lazy var startButton: UIButton = {
        
        let startBtn = UIButton()
        
        startBtn.setTitle("开始体验", forState: UIControlState.Normal)
        startBtn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        startBtn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        startBtn.sizeToFit()
        
        startBtn.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return startBtn
    }()
}